package com.learnspringcloud.product.service.impl;

import com.learnspringcloud.product.dto.CartDTO;
import com.learnspringcloud.product.dataobject.ProductInfo;
import com.learnspringcloud.product.enums.ProductStatusEnum;
import com.learnspringcloud.product.enums.ResultEnum;
import com.learnspringcloud.product.exception.ProductException;
import com.learnspringcloud.product.repository.ProductInfoRepository;
import com.learnspringcloud.product.service.ProductService;
import com.learnspringcloud.product.utils.JsonUtil;
import com.learnspringcloud.productcommon.ProductInfoOutput;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author Lin
 * @date 2018/9/20 0020
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductInfoRepository productInfoRepository;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public List<ProductInfo> findList(List<String> productIdList) {

        return productInfoRepository.findByProductIdIn(productIdList);
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public void decreaseStock(List<CartDTO> cartDTOList) {

        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = productInfoRepository.findById(cartDTO.getProductId())
                    .orElseThrow(() -> new ProductException(ResultEnum.PRODUCT_NOT_EXISTS));

            if (productInfo.getProductStock() < cartDTO.getProductQuantity()) {

                throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }

            productInfo.setProductStock(productInfo.getProductStock() - cartDTO.getProductQuantity());

            productInfoRepository.save(productInfo);

            ProductInfoOutput output = new ProductInfoOutput();
            BeanUtils.copyProperties(productInfo, output);
            // 发送MQ消息
            amqpTemplate.convertAndSend("productInfo", JsonUtil.toJson(output));
        }
    }
}
